<template>
    <div class="app-container">
        <el-form
            class="filters"
            ref="searchForm"
            :model="searchForm"
            label-width="75px"
            size="mini"
        >
            <el-row>
                <el-col :span="5">
                    <el-form-item label="设备编码" style="width: 100%">
                        <el-input
                            type="textarea"
                            :rows="3"
                            :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！输入示例：\nCC08DPC0202204250001\nCC08DPC0202205070001\n0000092011500063'"
                            v-model="searchForm.codes"
                            @change.native="keyUp($event)"
                            @input.native="keyInput($event)"
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="19" class="filters">
                    <el-form-item label="厂商" v-if="platformType == 'P'">
                        <el-select
                            v-model="searchForm.organizationId"
                            placeholder="请选择厂商"
                            @change="organizeChange"
                            clearable
                        >
                            <el-option
                                v-for="item in factuerOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="运营商">
                        <el-select
                            :disabled="!searchForm.organizationId"
                            v-model="searchForm.operatorId"
                            placeholder="请先选择厂商"
                            clearable
                        >
                            <el-option
                                v-for="item in operatorOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备类型">
                        <el-select
                            v-model="searchForm.equipTypeCode"
                            @change="equipTypeChange"
                            placeholder="请选择设备类型"
                            clearable
                        >
                            <el-option
                                v-for="item in equipTypeOption"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="部件">
                        <el-select
                            v-model="searchForm.partTypes"
                            :disabled="searchForm.equipTypeCode.length == 0"
                            multiple
                            placeholder="请选择部件"
                            clearable
                        >
                            <el-option
                                v-for="item in componentList"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务状态">
                        <el-select
                            v-model="searchForm.statuses"
                            multiple
                            placeholder="请选择业务状态"
                            clearable
                        >
                            <el-option
                                v-for="item in businessStatus"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="版本">
                        <el-input
                            v-model="searchForm.version"
                            placeholder="请输入版本"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="联网状态">
                        <el-select
                            v-model="searchForm.isOnline"
                            placeholder="请选择联网状态"
                            clearable
                        >
                            <el-option
                                v-for="item in isOnlineStatus"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="标签">
                        <el-select
                            v-model="searchForm.tagIds"
                            multiple
                            collapse-tags
                            placeholder="请选择标签"
                            clearable
                        >
                            <el-option
                                v-for="item in tagsOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="地区" class="area-select">
                        <el-cascader
                            :options="areaSelectData"
                            :props="areaSelectDataProps"
                            ref="areaSelectRef"
                            size="large"
                            v-model="searchForm.regionCode"
                            placeholder="请选择省市区"
                            @change="operateChange"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="详细地址">
                        <el-input
                            v-model="searchForm.address"
                            placeholder="请输入详细地址"
                            clearable
                        />
                    </el-form-item>
                    <div class="search-btns">
                        <el-button
                            :loading="exportBtnLoading"
                            type="success"
                            size="mini"
                            icon="el-icon-download"
                            @click="isExport"
                            >导出excel文件</el-button
                        >
                        <el-button
                            type="primary"
                            size="mini"
                            icon="el-icon-search"
                            @click="doSearch"
                            >搜索</el-button
                        >
                        <el-button
                            type="default"
                            size="mini"
                            icon="el-icon-refresh"
                            @click="resetSearch"
                            >重置</el-button
                        >
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="codes" slot-scope="scope">
                <div class="codes">
                    <span>{{ scope.row.code }}</span>
                    <img
                        v-if="scope.row.isOnline == 1"
                        src="@/assets/image/online.png"
                        alt=""
                    />
                    <img v-else src="@/assets/image/offline.png" alt="" />
                </div>
            </template>
            <template slot="tags" slot-scope="scope">
                <div class="tags-content">
                    <Tags
                        :currentRow="scope.row"
                        @updateList="fetchData"
                    ></Tags>
                    <!-- <i
                                    class="el-icon-circle-plus-outline"
                                    @click="tagSetShow(scope.row)"
                                ></i> -->
                </div>
            </template>
            <template slot="softVersion" slot-scope="scope">
                <span
                    style="text-align: left"
                    v-html="$options.filters.filterVersion(scope.row)"
                ></span>
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />
    </div>
</template>

<script>
import { partType, exportVersionFile } from "@/api/file";
import { equipment, operator } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import { businessStatus, isOnlineStatus } from "@/utils/config";
import { removeNullUndefined } from "@/utils/index.js";

import moment from "moment";
import Tags from "@/views/equipment/equipentry/components/tags.vue";

import { handleConfirm } from "@/utils/messageBox";

export default {
    components: { Pagination, Table, Dialog, Tags },
    filters: {
        filterVersion(item) {
            // 转换后的二维数组
            if (
                item.equipSoftwareVersions &&
                item.equipSoftwareVersions.length > 0
            ) {
                let arrayTwo = Object.values(
                    item.equipSoftwareVersions.reduce((res, item) => {
                        res[item.partType]
                            ? res[item.partType].push(item)
                            : (res[item.partType] = [item]);
                        return res;
                    }, {})
                );
                let jsons = "";
                arrayTwo.map((item, index) => {
                    jsons += "<div>" + item[0].partTypeName + "：";
                    item.filter((qq, inx) => {
                        jsons +=
                            item.length > 1
                                ? `<span class="addrId">${qq.addrId}</span> ${qq.version}；`
                                : qq.version;
                    });
                    // if (index < arrayTwo.length - 1) {jsons += "；";}
                    jsons += "</div>";
                });
                return jsons;
            } else {
                return "";
            }
        },
    },
    data() {
        return {
            list: null,
            listLoading: false,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                organizationId: "",
                equipTypeCode: "",
                operatorId: "",
                partType: [],
                statuses: [],
                version: "",
                isOnline: "",
                codes: "",
                regionCode: "",
                address: "",
                tagIds: [],
            },

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                { slot: "codes", label: "设备编码", width: "225" },
                {
                    label: "运营商",
                    prop: "operatorName",
                    wide: "130",
                },
                {
                    label: "设备类型",
                    prop: "equipTypeName",
                    wide: "78",
                },
                { slot: "tags", label: "标签", width: "130" },
                { slot: "softVersion", label: "版本" },
                {
                    label: "更新时间",
                    prop: "updateTime",
                    wide: "156",
                    formatter: (item) => {
                        return item.updateTime
                            ? moment(item.updateTime).format(
                                  "YYYY-MM-DD HH:mm:ss"
                              )
                            : "";
                    },
                },
            ],
            tableData: [],

            areaSelectData: [], // options绑定的数据就是引入的 provinceAndCityData
            areaSelectDataProps: {
                children: "childrens",
                value: "code",
                label: "name",
                emitPath: false,
            },
            operatorOption: [], //运营商option
            factuerOption: [], //厂商option
            equipTypeOption: [], //设备类型option
            businessStatus: businessStatus,
            isOnlineStatus: isOnlineStatus,
            componentList: [],
            platformType: this.$store.state.user.platformType,
            organizationId: this.$store.state.user.organizationId,

            tagsOption: [],
            exportBtnLoading: false,

            searchData: {},
        };
    },
    async created() {
        if (this.platformType != "P") {
            //非平台用户
            this.searchForm.organizationId = this.organizationId;
            this.organizeChange(this.organizationId);
        } else {
            this.factuerOption = await this.$store.dispatch(
                "operator/generatorFactuer"
            );
        }
        this.fetchData();
        this.getOperator();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            let param = { ...this.searchForm };

            if (param.codes) {
                param.codes = param.codes.split("\n").filter((item) => item);
            }
            if (param.codes.length == 1) {
                param.code = param.codes[0];
                delete param.codes;
            }
            equipment(
                "/version/list",
                "post",
                {
                    ...removeNullUndefined(param),
                },
                1
            )
                .then((res) => {
                    this.tableData = res.data;
                    this.total = +res.total;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        async getOperator() {
            this.areaSelectData = await this.$store.dispatch(
                "operator/generatorRegion"
            );
            this.equipTypeOption = await this.$store.dispatch(
                "operator/generatorEquipType"
            );
            this.tagsOption = await this.$store.dispatch(
                "operator/generatorTags"
            );
        },
        async equipTypeChange(e) {
            this.componentList = [];
            this.searchForm.partTypes = [];
            let data = await partType("/list", "get", { equipTypeCode: e });
            this.componentList = data.data;
        },
        async organizeChange(e) {
            this.operatorOption = [];
            this.searchForm.operatorId = "";
            if (e) {
                let datas = await operator("/all", "get", {
                    organizationId: e,
                });
                this.operatorOption = datas.data;
            }
        },

        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert("submit!");
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetDialogForm(formName) {
            this.$refs[formName].resetFields();
        },
        operateChange(e) {
        },

        //限制输入特殊字符
        keyUp(e) {
            let str = e.target.value.replace(
                /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                ""
            );
            e.target.value = str;
            this.searchForm.codes = str;
        },
        // 只能输入汉字、英文、数字
        keyInput(e) {
            let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
            e.target.value = str;
            this.searchForm.codes = str;
        },
        resetSearch() {
            this.searchForm = {
                pageNum: this.searchForm.pageNum,
                pageSize: this.searchForm.pageSize,
                organizationId:
                    this.platformType != "P" ? this.organizationId : "",
                equipTypeCode: "",
                operatorId: "",
                partTypes: [],
                statuses: [],
                version: "",
                isOnline: "",
                codes: "",
                regionCode: "",
                address: "",
                tagIds: [],
            };
            this.searchData = { ...this.searchForm };
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.searchData = { ...this.searchForm };
            this.fetchData();
        },
        isExport() {
            if(this.tableData.length==0){
                this.$message.error('暂无可导出数据~');
                return;
            }
            handleConfirm(`确定要导出excel文件吗？`, "warning", "提示")
                .then((res) => {
                    this.doExport();
                })
                .catch((err) => {
                    // do something cancel
                });
        },
        doExport() {
            this.exportBtnLoading = true;
            let param = { ...this.searchData };

            if (param.codes) {
                param.codes = param.codes.split("\n").filter((item) => item);
            }
            if (param.codes.length == 1) {
                param.code = param.codes[0];
                delete param.codes;
            }
            delete param.pageNum;
            delete param.pageSize;
            exportVersionFile({
                ...removeNullUndefined(param),
            })
                .catch((err) => {
                    const content = err.data; // 这里试试res 不行就用res.data
                    err.data.text().then((text) => {
                        if (typeof text == "string") {
                            try {
                                let obj = JSON.parse(text);
                                if (typeof obj == "object" && obj) {
                                    this.$message.error(obj.message);
                                    return false;
                                } else {
                                }
                            } catch (e) {
                                const blob = new Blob([content]); //构造一个blob对象来处理数据
                                const fileName = "版本查询excel文件.xlsx"; // 下载的文件名称 可以自定义
                                //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
                                //IE10以上支持blob但是依然不支持download
                                if ("download" in document.createElement("a")) {
                                    //支持a标签download的浏览器
                                    const link = document.createElement("a"); //创建a标签
                                    link.download = fileName; //a标签添加属性
                                    link.style.display = "none";
                                    link.href = URL.createObjectURL(blob);
                                    document.body.appendChild(link);
                                    link.click(); //执行下载
                                    URL.revokeObjectURL(link.href); //释放url
                                    document.body.removeChild(link); //释放标签
                                } else {
                                    //其他浏览器
                                    navigator.msSaveBlob(blob, fileName);
                                }
                            }
                        }
                    });
                })
                .finally((fin) => {
                    this.exportBtnLoading = false;
                });
        },
    },
};
</script>
<style lang="scss">
.el-cascader-panel {
    .el-scrollbar:first-child,
    .el-scrollbar:nth-child(2) {
        .el-checkbox {
            display: none;
        }
    }
}
</style>
<style scoped lang="scss">
@import "@/styles/common.scss";

.area-select {
    .el-cascader {
        width: 100%;
    }
}

.filters {
    .el-form-item {
        width: 16%;
    }
    .el-form-item__content {
        width: auto;
    }
}

.codes {
    @include flexLayout(center, center);

    img {
        width: 20px;
        margin-left: 10px;
    }
}

::v-deep .addrId {
    display: inline-block;
    width: 16px;
    height: 16px;
    line-height: 15px;
    font-size: 12px;
    border-radius: 50%;
    text-align: center;
    border: 1px solid #606266;
    transform: scale(0.95);
}
::v-deep .el-select__tags {
    .el-tag:first-child {
        max-width: 66%;
    }
}
</style>
